﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Service.Framework;
using Service.Framework.Utils;
using System.Reflection;
using Nacos.V2;
using Refit;
using Service.Framework.Attributes;

namespace Service.Core.OpenFegin
{
    public static class ServiceOpenFeginExtensions
    {
        /// <summary>
        /// 添加OpenFegin 服务
        /// </summary>
        /// <param name="builder"></param>
        public static void AddOpenFeginService(this WebApplicationBuilder builder)
        {
            builder.Services.AddTransient<ServiceDiscoveryHandler>();
            builder.Services.AddTransient<AuthenticatedHttpClientHandler>();
            var services = builder.Services;
            List<Type> list = (from type in DynamicInject._loadedAssemblies.SelectMany(assembly => assembly.GetTypes())
                               where type.IsDefined(typeof(FeginClientAttribute), inherit: false)
                               select type).ToList();
            //获取FeginClient 特性所有类
            foreach (var type in list)
            {
                var attr = type.GetCustomAttribute<FeginClientAttribute>();
                if (attr != null)
                {
                    RefitSettings refitSettings = new RefitSettings()
                    {
                        ContentSerializer = new NewtonsoftJsonContentSerializer(new Newtonsoft.Json.JsonSerializerSettings()
                        {
                            ContractResolver = new CustomContractResolver(),
                            DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.IgnoreAndPopulate,
                            NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                        })
                    };
                    services.AddRefitClient(type, refitSettings)
                        .ConfigureHttpClient((serviceProvider, client) =>
                        {
                            if (!string.IsNullOrWhiteSpace(attr.BaseAddress))
                            {
                                client.BaseAddress = new Uri(attr.BaseAddress);
                            }
                            else
                            {
                                var host = new Uri($"http://{attr.ServiceName}");
                                client.BaseAddress = host;

                            }
                        }).AddHttpMessageHandler<ServiceDiscoveryHandler>()
                        .AddHttpMessageHandler<AuthenticatedHttpClientHandler>();
                }
            }


        }
    }
}
